package com.lch.netty.nio.buffer;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Objects;

/**
 * 直接缓冲区
 *
 * @author: liuchenhui
 * @create: 2019-10-14 10:19
 **/
public class DirectBuffer {

    public static void main(String[] args) throws IOException {
        String path = Objects.requireNonNull(DirectBuffer.class.getClassLoader().getResource("test.txt")).getPath();
        FileInputStream fileInputStream = new FileInputStream(path);
        FileChannel fileChannel = fileInputStream.getChannel();

        String copypath = path.replace("test", "copytest");
        FileOutputStream copyFileInputStream = new FileOutputStream(copypath);
        FileChannel channel = copyFileInputStream.getChannel();

        System.out.println(path);
        System.out.println(copypath);
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);

        while (true) {
            byteBuffer.clear();
            int r = fileChannel.read(byteBuffer);
            if (r == -1) {
                break;
            }
            byteBuffer.flip();
            channel.write(byteBuffer);
        }
        fileChannel.close();
        channel.close();
        fileInputStream.close();
        copyFileInputStream.close();
    }
}
